package com.zhiyou100.properties;

import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Enumeration;
import java.util.Properties;

public class Demo2 {

    public static void main(String[] args) throws IOException {

        String path = "./day2_10/src/user.properties";
        //创建一个properties对象
        Properties properties = new Properties();
        //利用流读取文件
        FileInputStream fis = new FileInputStream(path);
        //将输入流加载到properties对象中
        properties.load(fis);

        //获取属性名列表
        Enumeration<?> names = properties.propertyNames();
        User user = new User();
        //遍历属性列表，同时借助反射根据属性key值前缀将数据封装到对应对象中
        while (names.hasMoreElements()) {
            String element = (String) names.nextElement();
            //属性key值前缀
            String prefix = element.substring(0, element.indexOf("."));
            if (prefix.equals("user")) {
                //key值后缀
                String suffix = element.substring(element.indexOf(".") + 1);
                //获取User对象运行时类对象
                Class<? extends User> userClass = user.getClass();
                //获取目标类对象的所有声明字段
                Field[] fields = userClass.getDeclaredFields();
                for (Field field : fields) {
                    //如果属性后缀与字段名一致
                    if (field.getName().equals(suffix)) {
                        //获取属性类型
                        Class<?> type = field.getType();
//                        //获取类型名称
//                        String name = type.getName();
                        try {
                            if (type.equals(int.class)) {
                                field.setInt(user, Integer.parseInt(properties.getProperty(element)));
                            } else {
                                field.set(user, properties.getProperty(element));
                            }
                        } catch (IllegalAccessException e) {
                            field.setAccessible(true);
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        System.out.println("user = " + user);



    }


}
